﻿using BLE_Keypad_Tool.Classes;
using BLE_Keypad_Tool_Controls;
using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

namespace BLE_Keypad_Tool
{
	public partial class FormKeypad : Form
	{
		private readonly KeyPad _keypad;
		private Key[] _keys;

		public FormKeypad(KeyPad keypad)
		{
			InitializeComponent();
			_keypad = keypad;
		}

		private void FormKeypad_Load(object sender, EventArgs e)
		{
			EnableDoubleBuffered(PanelKeypad);
			initialized_keypad_layout();
		}

		private void initialized_keypad_layout()
		{
			PanelKeypad.Controls.Clear();

			_keys = new Key[_keypad.key_counts];

			for (int index=0; index < _keypad.key_counts; index++)
			{
				_keys[index] = new Key
				{
					Name = $"key_{index}",
					Index = index,
					KeyIndex = _keypad.key_map[0][index],
					KeyCode = _keypad.key_map[1][index],
					Legend = KeyCode.get_keycode_name(_keypad.key_map[1][index]),
					Parent = PanelKeypad
				};
				_keys[index].Location = new Point(
					index % 8 * _keys[index].KeyWidthPixel + index % 8 * 2,
					index / 8 * _keys[index].KeyHeightPixel + index / 8 * 2
				);
			}
		}

		/// <summary>
		/// 启用控件双缓存处理
		/// </summary>
		/// <param name="control"></param>
		private void EnableDoubleBuffered(Control control)
		{
			control.GetType().GetProperty(
				"DoubleBuffered",
				BindingFlags.Instance | BindingFlags.NonPublic
			).SetValue(control, true, null);
		}
	}
}
